package com.ruoyi.quartz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.useralignment.CombatBlogWb;
import com.ruoyi.combat.domain.useralignment.CombatRelationWb;
import com.ruoyi.combat.domain.useralignment.CombatUserWb;
import com.ruoyi.combat.domain.userlocation.CombatBlog;
import com.ruoyi.combat.domain.userlocation.CombatRelation;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.service.useralignment.*;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.util.weibo.WeiboApiUtil;
import com.ruoyi.combat.util.zhihu.ZhihuApiUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 课题五
 */
@Component("useralignmentTask")
@Slf4j
public class UseralignmentTask {

    @Autowired
    private ICombatBlogWbService combatBlogWbService;
    @Autowired
    private ICombatUserWbService combatUserWbService;
    @Autowired
    private ICombatUserZhService combatUserZhService;
    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private ICombatRelationWbService combatRelationWbService;
    @Autowired
    private ICombatHeavyUserService combatHeavyUserService;
    @Autowired
    private WeiboApiUtil weiboApiUtil;
    @Autowired
    private ZhihuApiUtil zhihuApiUtil;



    public void collectionZH(){
        log.info("定时采集知乎数据");
        combatUserZhService.crawlAllZhByUserIds();
    }

    /**
     * 采集定时微博数据
     */
    public void collection(){
        log.info("定时采集微博数据");
        List<CombatUserWb> combatUserWbs = combatUserWbService.selectCombatUserWbList(new CombatUserWb());
        List<CombatUser> listData = combatUserService.selectCombatUserList(new CombatUser());

        Map<String,Map> dataMap = new HashMap<>();
        for (CombatUser user : listData) {
            String userId = user.getUserId();
            //我是调取爬虫接口的逻辑代码
            String token = user.getToken();
            Map<String, String> data = new HashMap<>();
            if (StringUtils.isNotEmpty(token)) {
                data.put("type", "follow");
                data.put("cookie", token);
                data.put("user_id", userId);
            }
            dataMap.put(userId,data);
        }
        for (CombatUserWb user : combatUserWbs) {
            String userId = user.getUserId();
            //我是调取爬虫接口的逻辑代码
            String token = user.getToken();
            Map<String, String> data = new HashMap<>();
            if (StringUtils.isNotEmpty(token)) {
                data.put("type", "follow");
                data.put("cookie", token);
                data.put("user_id", userId);
            }
            dataMap.put(userId,data);
        }
        List<Map<String, String>> listMap = new ArrayList<>();
        List<String> list = new ArrayList<>();
        dataMap.keySet().stream().forEach(userId -> {
            list.add(userId);
            Map map = dataMap.get(userId);
            if(map.get("user_id")!=null){
                listMap.add(map);
            }
        });
        String latestWeibo = weiboApiUtil.getLatestWeibo(list);
        String friends = weiboApiUtil.getFriends(listMap);
    }


    /**
     * 采集一天的微博数据
     */
    public void collectionWb(){
        log.info("定时采集微博数据");
        List<CombatUserWb> combatUserWbs = combatUserWbService.selectCombatUserWbList(new CombatUserWb());
        Map<String,Map> dataMap = new HashMap<>();
        for (CombatUserWb user : combatUserWbs) {
            String userId = user.getUserId();
            //我是调取爬虫接口的逻辑代码
            String token = user.getToken();
            Map<String, String> data = new HashMap<>();
            if (StringUtils.isNotEmpty(token)) {
                data.put("type", "follow");
                data.put("cookie", token);
                data.put("user_id", userId);
            }
            dataMap.put(userId,data);
        }
        List<Map<String, String>> listMap = new ArrayList<>();
        List<String> list = new ArrayList<>();
        dataMap.keySet().stream().forEach(userId -> {
            list.add(userId);
            Map map = dataMap.get(userId);
            if(map.get("user_id")!=null){
                listMap.add(map);
            }
        });
        String latestWeibo = weiboApiUtil.getLatestWeiboOneDay(list);
        String friends = weiboApiUtil.getFriends(listMap);
    }

    /**
     * 采集最新的博文数据
     * @param data
     */
    public void makeBlogData(String data){
        Map bean = JSONUtil.toBean(data, Map.class);
        Object o = bean.get("statuses");
        if(o!=null){
            JSONArray statuses = (JSONArray) o;
            if(statuses.size()>0){
                for (int i = 0; i < statuses.size(); i++){
                    Object o1 = statuses.get(i);
                    Map bean1 = JSONUtil.toBean(String.valueOf(o1), Map.class);
                    String idstr = String.valueOf(bean1.get("idstr"));
                    CombatBlogWb combatBlog = new CombatBlogWb();
                    combatBlog.setBlogId(idstr);
                    List<CombatBlogWb> combatBlogs = combatBlogWbService.selectCombatBlogWbList(combatBlog);
                    if(combatBlogs.size()<=0){
                        Map user = (Map) bean1.get("user");
                        combatBlog.setUserId(String.valueOf(user.get(idstr)));
                        combatBlog.setUserName(String.valueOf(user.get("screen_name")));
                        String time = String.valueOf(bean1.get("created_at"));
                        combatBlog.setReportime(DateUtil.parse(time,"EEE MMM dd HH:mm:ss Z yyyy"));
                        combatBlog.setReportContent(String.valueOf(bean1.get("text")));
                        Object o2 = bean1.get("pic_urls");
                        if(o2!=null) {
                            String reportImages = "";
                            List<Map> list = (List<Map>) bean1.get("pic_urls");
                            for (Map map : list){
                                if(StringUtils.isNotEmpty(reportImages)){
                                    reportImages = reportImages + "," + String.valueOf(map.get("thumbnail_pic"));
                                }else {
                                    reportImages = String.valueOf(map.get("thumbnail_pic"));
                                }
                                combatBlog.setReportImages(reportImages);
                            }
                        }
                        combatBlog.setCrawltime(new Date());
                        combatBlog.setBlogPlate("微博");
                        if(bean1.get("comments_count")==null){
                            combatBlog.setBlogCommentNum(0l);
                        }else {
                            String s = String.valueOf(bean1.get("comments_count"));
                            combatBlog.setBlogCommentNum(Long.parseLong(s));
                        }

                        Object o3 = bean1.get("reposts_count");
                        if(o3==null){
                            combatBlog.setBlogForwardNum(0l);
                        }else {
                            String s = String.valueOf(bean1.get("reposts_count"));
                            combatBlog.setBlogForwardNum(Long.parseLong(s));
                        }
                        Object o4 = bean1.get("attitudes_count");
                        if(o4==null){
                            combatBlog.setBlogTolikeNum(0l);
                        }else {
                            String s = String.valueOf(bean1.get("attitudes_count"));
                            combatBlog.setBlogTolikeNum(Long.parseLong(s));
                        }
//                        combatBlog.setStatus("0");
                        combatBlogWbService.insertCombatBlogWb(combatBlog);
                    }
                }
            }
        }
    }

    /**
     * c采集用户最新关注数据
     * @param data
     * @param userId
     */
    public void makefriendsData(String data,String userId){
        CombatUserWb combatUser = combatUserWbService.selectCombatUserWbByUserId(userId);
        Map bean = JSONUtil.toBean(data, Map.class);
        Object o = bean.get("users");
        if(o!=null){
            JSONArray users = (JSONArray) o;
            for (int i = 0; i < users.size(); i++) {
                Object o1 = users.get(i);
                Map user = JSONUtil.toBean(String.valueOf(o1), Map.class);
                String targetid = String.valueOf(user.get("idstr"));
                CombatRelationWb combatRelation = new CombatRelationWb();
                combatRelation.setUserid(userId);
                combatRelation.setTargetid(targetid);
                List<CombatRelationWb> combatRelations = combatRelationWbService.selectCombatRelationWbList(combatRelation);
                if(combatRelations.size()<=0){
                    combatRelation.setRelation("关注");
                    combatRelation.setPlate("微博");
                    combatRelation.setUsername(combatUser.getUserNickname());
                    combatRelation.setUserCity(combatUser.getUserHomeAddr());
                    combatRelation.setTargetName(String.valueOf(user.get("screen_name")));
                    combatRelation.setTargetCity(String.valueOf(user.get("city")));
                    combatRelationWbService.insertCombatRelationWb(combatRelation);
                }else{
                    //更新用户关注状态
                    CombatRelationWb combatRelation1 = combatRelations.get(0);
                    if("1".equals(combatRelation1.getStatus())){
                        combatRelation1.setStatus("0");
                        combatRelationWbService.updateCombatRelationWb(combatRelation1);
                    }
                }
            }
        }
    }

    /**
     * 定时检测重保用户
     */
    public void checkHeavyUserList(){
        combatHeavyUserService.checkHeavyUserList();
    }
}
